using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace TestScript
{
    public class ScreenshotCapture : MonoBehaviour
    {
        // 在Inspector视图中将相机拖放到这个字段中
        public Camera screenshotCamera;

        // 截图的文件名前缀
        public string screenshotPrefix = "Screenshot";

        
        // 截图的宽度和高度
        public int screenshotWidth = 300;
        public int screenshotHeight = 300;
        
        // 按钮点击后触发截图
        public void CaptureScreenshot()
        {
            // 创建一个Texture2D来存储截图
            Texture2D screenshotTexture = new Texture2D(screenshotWidth, screenshotHeight, TextureFormat.RGB24, false);

            // 读取相机渲染纹理到Texture2D
            screenshotCamera.targetTexture = RenderTexture.GetTemporary(screenshotWidth, screenshotHeight, 24);
            screenshotCamera.Render();
            RenderTexture.active = screenshotCamera.targetTexture;
            screenshotTexture.ReadPixels(new Rect(0, 0, screenshotWidth, screenshotHeight), 0, 0);
            screenshotTexture.Apply();

            // 重置相机渲染纹理
            screenshotCamera.targetTexture = null;
            RenderTexture.active = null;

            // 将Texture2D保存为PNG文件
            byte[] bytes = screenshotTexture.EncodeToPNG();
            string filename = screenshotPrefix + "_" + System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".png";
            
            
            System.IO.File.WriteAllBytes(filename, bytes);

            // 销毁Texture2D对象
            Destroy(screenshotTexture);

            Debug.Log("截图已保存至：" + filename);
        }

        private void Update()
        {
            if (Input.GetKeyUp(KeyCode.P))
            {
                CaptureScreenshot();
            }
        }
    }

}
